package com.swpu.service_remind.xxl_executor;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.swpu.service_remind.config.RabbitExChangeConfig;
import com.swpu.service_remind.entity.CheckupRemind;
import com.swpu.service_remind.entity.MedicineRemind;
import com.swpu.service_remind.entity.SitRemind;
import com.swpu.service_remind.entity.vo.DrinkMessageVO;
import com.swpu.service_remind.entity.DrinkRemind;
import com.swpu.service_remind.entity.vo.MedicineMessageVo;
import com.swpu.service_remind.entity.vo.MessageVo;
import com.swpu.service_remind.service.CheckupRemindService;
import com.swpu.service_remind.service.DrinkRemindService;
import com.swpu.service_remind.service.MedicineRemindService;
import com.swpu.service_remind.service.SitRemindService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component("xxljobHandleExecutor")
public class XxlJobExecutor {
    private static Logger logger = LoggerFactory.getLogger(XxlJobExecutor.class);
    @Autowired
    private DrinkRemindService drinkRemindService;
    @Autowired
    private MedicineRemindService medicineRemindService;
    @Autowired
    private SitRemindService sitRemindService;
    @Autowired
    private CheckupRemindService checkupRemindService;
    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("drinkRemindJobHandler")
    public void drinkRemindJobHandler() {
        List<DrinkRemind> remindList = drinkRemindService.list(null);
        for (DrinkRemind drinkRemind : remindList) {
            List<Message> messages = this.generateDrinkMessages(drinkRemind);
            for (Message message : messages) {
                CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                rabbitTemplate.send(RabbitExChangeConfig.DESTINATION_NAME, RabbitExChangeConfig.SMS_ROUTING_KEY, message, correlationData);
            }
        }
        System.out.println("消息发送--------");
    }

    @XxlJob("medicineRemindHandler")
    public void medicineRemindHandler() {
        List<MedicineRemind> remindsList = medicineRemindService.list(null);
        for (MedicineRemind medicineRemind : remindsList) {
            List<Message> messages = this.generateMedicineMqMessages(medicineRemind);
            System.out.println(messages);
            for (Message message : messages) {
                CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                rabbitTemplate.send(RabbitExChangeConfig.DESTINATION_NAME, RabbitExChangeConfig.SMS_ROUTING_KEY, message, correlationData);
            }
        }

        System.out.println("已发送消息");
    }

    @XxlJob("sitRemindHandler")
    public void sitRemindHandler() {
        List<SitRemind> remindsList = sitRemindService.list(null);
        for (SitRemind sitRemind : remindsList) {
            List<Message> messages = this.generateSitRemindMessages(sitRemind);
            System.out.println(messages);
            for (Message message : messages) {
                CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                rabbitTemplate.send(RabbitExChangeConfig.DESTINATION_NAME, RabbitExChangeConfig.SMS_ROUTING_KEY, message, correlationData);
            }
        }
        System.out.println("已发送消息");
    }

    @XxlJob("checkupRemindHandler")
    public void checkupRemindHandler() {
        LambdaQueryWrapper<CheckupRemind> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckupRemind::getAdded,0);
        List<CheckupRemind> checkupRemindList = checkupRemindService.list(wrapper);
        for (CheckupRemind checkupRemind : checkupRemindList) {
            List<Message> messages = this.generateCheckupRemindMessages(checkupRemind);
            System.out.println(messages);
            for (Message message : messages) {
                CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                rabbitTemplate.send(RabbitExChangeConfig.DESTINATION_NAME, RabbitExChangeConfig.SMS_ROUTING_KEY, message, correlationData);
                checkupRemind.setAdded(1);
                checkupRemindService.updateById(checkupRemind);
            }
        }
        System.out.println("已发送消息");
    }

    public List<Message> generateCheckupRemindMessages(CheckupRemind checkupRemind) {
        //     DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        //当天接受通知消息的开始时间
        //创建消息
        String dateFormatStr = DateUtil.format(checkupRemind.getCheckupDate(), "yyyy-MM-dd HH:mm:ss");
        ArrayList<Message> messageList = new ArrayList<>();
        MessageVo MessageVO = new MessageVo();
        MessageVO.setMessageType(4);
        MessageVO.setDate(dateFormatStr);
        MessageVO.setUserId(checkupRemind.getUserId());
        MessageProperties messageProperties = new MessageProperties();
        DateTime beginOfDay = DateUtil.beginOfDay(checkupRemind.getCheckupDate());
        //当天八点提醒
        DateTime dateTime = DateUtil.offsetHour(beginOfDay, 8);
        if(dateTime.isBefore(checkupRemind.getCheckupDate())){
            messageProperties.setExpiration(String.valueOf(dateTime.getTime() - new Date().getTime()));
        }else {
            messageProperties.setExpiration(String.valueOf(checkupRemind.getCheckupDate().getTime() - new Date().getTime()));
        }
       // messageProperties.setExpiration(String.valueOf(checkupRemind.getCheckupDate().getTime() - new Date().getTime()));
        System.out.println("消息给期时间" + String.valueOf(checkupRemind.getCheckupDate().getTime() - new Date().getTime()));
        if (checkupRemind.getEnableSms() == 1) {
            MessageVO.setEnableSms(1);
        } else MessageVO.setEnableSms(0);
        if (checkupRemind.getEnableWx() == 1) {
            MessageVO.setEnableWx(1);
        } else MessageVO.setEnableWx(0);
        System.out.println("开始创建");
        if (Integer.valueOf(messageProperties.getExpiration()) > 0) {
            Message message = new Message(JSON.toJSONString(MessageVO).getBytes(StandardCharsets.UTF_8), messageProperties);
            messageList.add(message);
        }
        System.out.println("消息创建完成");
        return messageList;
    }


    public List<Message> generateSitRemindMessages(SitRemind sitRemind) {
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        String startHourTime = sitRemind.getStartHour();
        String endHourTime = sitRemind.getEndHour();
        //当天接受通知消息的开始时间
        Integer startHour = Integer.valueOf(startHourTime.substring(0, 2));
        Integer startMinutes = Integer.valueOf(startHourTime.substring(3));
        DateTime basicTime = DateUtil.offsetMillisecond(beginOfDay, startHour * 3600 * 1000 + startMinutes * 60 * 1000);
        //当天接受通知消息的结束时间
        Integer endHour = Integer.valueOf(endHourTime.substring(0, 2));
        Integer endMinutes = Integer.valueOf(endHourTime.substring(3));
        DateTime endTime = DateUtil.offsetMillisecond(beginOfDay, endHour * 3600 * 1000 + endMinutes * 60 * 1000);
        DateTime tempTime = basicTime;
        //创建消息
        ArrayList<Message> messageList = new ArrayList<>();
        while (tempTime.isBefore(endTime)) {
            MessageProperties messageProperties = new MessageProperties();
            //设置过期时间
            //messageProperties.setExpiration("10000");
            messageProperties.setExpiration(String.valueOf(tempTime.getTime() - new Date().getTime()));
            System.out.println("消息给期时间" + String.valueOf(tempTime.getTime() - new Date().getTime()));
            //这个参数是用来做消息的唯一标识
            //发布消息时使用，存储在消息的headers中
            // CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            String dateFormatStr = DateUtil.format(tempTime, "yyyy-MM-dd HH:mm:ss");
            MessageVo MessageVO = new MessageVo();
            MessageVO.setDate(dateFormatStr);
            MessageVO.setUserId(sitRemind.getUserId());
            MessageVO.setMessageType(3);
            if (sitRemind.getEnableSms() == 1) {
                MessageVO.setEnableSms(1);
            } else MessageVO.setEnableSms(0);
            if (sitRemind.getEnableWx() == 1) {
                MessageVO.setEnableWx(1);
            } else MessageVO.setEnableWx(0);
            if (Integer.valueOf(messageProperties.getExpiration()) > 0) {
                Message message = new Message(JSON.toJSONString(MessageVO).getBytes(StandardCharsets.UTF_8), messageProperties);
                messageList.add(message);
            }

            tempTime = DateUtil.offsetHour(tempTime, sitRemind.getDuration());
        }
        return messageList;
    }

    public List<Message> generateDrinkMessages(DrinkRemind drinkRemind) {
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        String startHourTime = drinkRemind.getStartHour();
        String endHourTime = drinkRemind.getEndHour();
        //当天接受通知消息的开始时间
        Integer startHour = Integer.valueOf(startHourTime.substring(0, 2));
        Integer startMinutes = Integer.valueOf(startHourTime.substring(3));
        DateTime basicTime = DateUtil.offsetMillisecond(beginOfDay, startHour * 3600 * 1000 + startMinutes * 60 * 1000);
        //当天接受通知消息的结束时间
        Integer endHour = Integer.valueOf(endHourTime.substring(0, 2));
        Integer endMinutes = Integer.valueOf(endHourTime.substring(3));
        DateTime endTime = DateUtil.offsetMillisecond(beginOfDay, endHour * 3600 * 1000 + endMinutes * 60 * 1000);
        DateTime tempTime = basicTime;
        //创建消息
        System.out.println("开始创建");
        ArrayList<Message> messageList = new ArrayList<>();
        while (tempTime.isBefore(endTime)) {
            MessageProperties messageProperties = new MessageProperties();
            //设置过期时间
            //messageProperties.setExpiration("10000");
            messageProperties.setExpiration(String.valueOf(new Date().getTime() - tempTime.getTime()));
            System.out.println("消息给期时间" + String.valueOf(new Date().getTime() - tempTime.getTime()));
            //这个参数是用来做消息的唯一标识
            //发布消息时使用，存储在消息的headers中
            // CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            String dateFormatStr = DateUtil.format(tempTime, "yyyy-MM-dd HH:mm:ss");
            DrinkMessageVO drinkMessageVO = new DrinkMessageVO();
            drinkMessageVO.setDate(dateFormatStr);
            drinkMessageVO.setUserId(drinkRemind.getUserId());
            drinkMessageVO.setMessageType(1);
            if (drinkRemind.getEnableSms() == 1) {
                drinkMessageVO.setEnableSms(1);
            } else drinkMessageVO.setEnableSms(0);
            if (drinkRemind.getEnableWx() == 1) {
                drinkMessageVO.setEnableWx(1);
            } else drinkMessageVO.setEnableWx(0);
            Message message = new Message(JSON.toJSONString(drinkMessageVO).getBytes(StandardCharsets.UTF_8), messageProperties);
            messageList.add(message);
            tempTime = DateUtil.offsetHour(tempTime, drinkRemind.getDuration());
        }
        return messageList;
    }


    //生成用药提醒消息
    public List<Message> generateMedicineMqMessages(MedicineRemind medicineRemind) {
        Date nowDay = new Date();
        DateTime beginOfWeek = DateUtil.beginOfWeek(new Date());
        String[] weekNumberStr = medicineRemind.getWeekday().split(",");
        ArrayList<Message> messageList = new ArrayList<>();
        String[] hourTimeStrS = medicineRemind.getTimePoints().split(",");
        DateTime temp = beginOfWeek;
        for (int i = 0; i < weekNumberStr.length; i++) {
            if (weekNumberStr[i].equals("1")) {
                for (String hourTimeStr : hourTimeStrS) {
                    DateTime offsetTime = DateUtil.offsetMillisecond(temp, getMillisecond(hourTimeStr));
                    System.out.println(offsetTime);
                    if (offsetTime.isAfter(nowDay)) {
                        MessageProperties messageProperties = new MessageProperties();
                        MedicineMessageVo medicineMessageVo = new MedicineMessageVo();
                        messageProperties.setExpiration((offsetTime.getTime() - nowDay.getTime()) + "");
                        String dateFormatStr = DateUtil.format(offsetTime, "yyyy-MM-dd HH:mm:ss");
                        medicineMessageVo.setDate(dateFormatStr);
                        medicineMessageVo.setEnableSms(medicineRemind.getEnableSms());
                        medicineMessageVo.setEnableWx(medicineRemind.getEnableWx());
                        medicineMessageVo.setUserId(medicineRemind.getUserId());
                        medicineMessageVo.setMessageType(2);
                        medicineMessageVo.setMedicineRemindId(medicineRemind.getId());
                        Message message = new Message(JSON.toJSONString(medicineMessageVo).getBytes(StandardCharsets.UTF_8), messageProperties);
                        messageList.add(message);
                    }
                }
            }
            temp = DateUtil.offsetDay(temp, 1);
        }
        System.out.println("生成消息完毕");
        return messageList;
    }

    public static int getMillisecond(String hourTimeStr) {
        Integer hour = Integer.valueOf(hourTimeStr.substring(0, 2));
        Integer minute = Integer.valueOf(hourTimeStr.substring(3));
        return (hour * 3600 + minute * 60) * 1000;
    }


    /**
     * 2、分片广播任务
     */
    @XxlJob("shardingJobHandler")
    public void shardingJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        // 业务逻辑
        for (int i = 0; i < shardTotal; i++) {
            if (i == shardIndex) {
                XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
            } else {
                XxlJobHelper.log("第 {} 片, 忽略", i);
            }
        }

    }


    /**
     * 3、命令行任务
     */
    @XxlJob("commandJobHandler")
    public void commandJobHandler() throws Exception {
        String command = XxlJobHelper.getJobParam();
        int exitValue = -1;

        BufferedReader bufferedReader = null;
        try {
            // command process
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command(command);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();
            //Process process = Runtime.getRuntime().exec(command);

            BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

            // command log
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                XxlJobHelper.log(line);
            }

            // command exit
            process.waitFor();
            exitValue = process.exitValue();
        } catch (Exception e) {
            XxlJobHelper.log(e);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        if (exitValue == 0) {
            // default success
        } else {
            XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
        }

    }


    /**
     * 4、跨平台Http任务
     * 参数示例：
     * "url: http://www.baidu.com\n" +
     * "method: get\n" +
     * "data: content\n";
     */
    @XxlJob("httpJobHandler")
    public void httpJobHandler() throws Exception {

        // param parse
        String param = XxlJobHelper.getJobParam();
        if (param == null || param.trim().length() == 0) {
            XxlJobHelper.log("param[" + param + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }

        String[] httpParams = param.split("\n");
        String url = null;
        String method = null;
        String data = null;
        for (String httpParam : httpParams) {
            if (httpParam.startsWith("url:")) {
                url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
            }
            if (httpParam.startsWith("method:")) {
                method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
            }
            if (httpParam.startsWith("data:")) {
                data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
            }
        }

        // param valid
        if (url == null || url.trim().length() == 0) {
            XxlJobHelper.log("url[" + url + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }
        if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
            XxlJobHelper.log("method[" + method + "] invalid.");

            XxlJobHelper.handleFail();
            return;
        }
        boolean isPostMethod = method.equals("POST");

        // request
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();

            // connection setting
            connection.setRequestMethod(method);
            connection.setDoOutput(isPostMethod);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(3 * 1000);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

            // do connection
            connection.connect();

            // data
            if (isPostMethod && data != null && data.trim().length() > 0) {
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.write(data.getBytes("UTF-8"));
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            // valid StatusCode
            int statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
            }

            // result
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            String responseMsg = result.toString();

            XxlJobHelper.log(responseMsg);

            return;
        } catch (Exception e) {
            XxlJobHelper.log(e);

            XxlJobHelper.handleFail();
            return;
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception e2) {
                XxlJobHelper.log(e2);
            }
        }

    }

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
    public void demoJobHandler2() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");
    }

    public void init() {
        logger.info("init");
    }

    public void destroy() {
        logger.info("destroy");
    }


}
